﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;

namespace WFL.Utils
{
    public static class BinaryFormatHelper
    {
        public static byte[] Serialize(object obj)
        {
            BinaryFormatter bf = new BinaryFormatter();
            MemoryStream ms = new MemoryStream();
            try
            {
                bf.Serialize(ms, obj);
                return ms.ToArray();
            }
            finally
            {
                ms.Close();
            }
        }

        public static void SerializeToFile(object obj, string filePath)
        {
            BinaryFormatter bf = new BinaryFormatter();
            FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None);
            try
            {
                bf.Serialize(fs, obj);
                fs.Flush();
            }
            finally
            {
                fs.Close();
            }
        }

        public static object Deserialize(byte[] buffer)
        {
            BinaryFormatter bf = new BinaryFormatter();
            MemoryStream ms = new MemoryStream(buffer);
            try
            {
                return bf.Deserialize(ms);
            }
            finally
            {
                ms.Close();
            }
        }

        public static object DeserializeFromFile(string filePath)
        {
            BinaryFormatter bf = new BinaryFormatter();
            FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
            try
            {
                return bf.Deserialize(fs);
            }
            finally
            {
                fs.Close();
            }
        }


    }
}
